package com.ztesoft.book.common.utils.validator;

import com.ztesoft.book.common.utils.exception.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;


/**
 * @Description hibernate-validator校验工具类，校验后通过ServiceException返回，方便异常统一管理
 * @Author YangFan
 * @Date 2021-06-22 17:28
 */
public final class ValidatorUtils {

    private static Validator validator;

    private ValidatorUtils() {
    }

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 方法功能描述:
     * < 校验对象 >
     *
     * @param object 【参数 1 注释说明】
     * @param groups 【参数 2 注释说明】
     * @return void                            【返回值 注释说明】
     * @author YangFan
     * @date 2021-06-22 17:28
     */
    public static void validateEntity(Object object, Class<?>... groups) throws ServiceException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append("\r\n");
            }
            throw new ServiceException(msg.toString());
        }
    }
}
